package com.atmilan.quartz.utils.source;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.StockAreaTempEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.coltorti.ColtortiProduct;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.crmeb.SupplierDiscount;
import com.atmilan.quartz.model.result.PriceResult;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.service.SupplierDiscountService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.util.StringUtil;

/**
 * 处理源数据转换和计算相关信息
 * @Description: 
 * @author daigb
 * @date 2021-03-05
 */
@Service
public class SourceColtortiProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;
    @Autowired
    SupplierDiscountService supplierDiscountService;

    /**
     * 构建DO对象
     * @Description:  
     * @author daigb 
     * @param @param product
     * @param @param productSkus
     * @param @return
     * @return StoreProductRequest
     * @throws
     */
    public StoreProductCrmebRequest buildColtortiProduct(ColtortiProduct product) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = new StoreProductCrmebRequest();
        String keyword = product.getSkuSupplier();
        String ean = product.getEan();
        if(StringUtils.isNotBlank(ean)) {
        	String[] eans = product.getEan().split(",");
        	for(String e : eans) {
        		if(StringUtils.isNotBlank(e)) {
        			keyword = e.length() > 10 ? e.substring(0, 10) : e;
        			break;
        		}
        	}
        }
        if (product.getBrand().equalsIgnoreCase("BURBERRY")) {
            keyword = product.getSkuSupplier();
        }
        try {
            // 轮播图
            JSONArray gallery = new JSONArray();
            if(StringUtil.isNotEmpty(product.getImage())) {
                gallery.add(product.getImage());
            }
            if(StringUtil.isNotEmpty(product.getImage1())) {
                gallery.add(product.getImage1());
            }
            if(StringUtil.isNotEmpty(product.getImage2())) {
                gallery.add(product.getImage2());
            }
            if(StringUtil.isNotEmpty(product.getImage3())) {
                gallery.add(product.getImage3());
            }
            if(0 >= gallery.size()) {
            	return null;
            }
            // 主图
            String mainImage = gallery.getString(0);
            // 原价
            BigDecimal otPrice = new BigDecimal(product.getRetailPrice().replaceAll("Eur", "").replaceAll(",", "").replaceAll(" ", ""));
            // 成本价
            String star = product.getStar();
            BigDecimal discount = new BigDecimal(product.getDiscount().replace("%", ""));
            discount = discount.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN);
            BigDecimal price = otPrice.multiply(BigDecimal.ONE.subtract(discount)).setScale(2, BigDecimal.ROUND_HALF_UP);

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier :: getBarcode, BarCodeEnum.COLTORTI.getCode())
                    .last("LIMIT 1")
            );
            if(null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }

            if("false".equals(star)) {
                SupplierDiscount supplierDiscount = Optional.ofNullable(supplierDiscountService.getOne(Wrappers.<SupplierDiscount>lambdaQuery().eq(SupplierDiscount::getSupplierId, productRequest.getSuppliersId())
                        .le(SupplierDiscount::getStartTime,new Date())
                        .ge(SupplierDiscount::getEndTime, new Date()).last("LIMIT 1"))).orElse(new SupplierDiscount());
                //2023.6.14折扣去掉
                price = price.multiply(BigDecimal.ONE.subtract(supplierDiscount.getDiscount() == null ? new BigDecimal("0") : new BigDecimal(supplierDiscount.getDiscount().toString()).movePointLeft(2)));
            }
            // 计算汇率和处理税率
            otPrice = otPrice.multiply(new BigDecimal("1.22")).setScale(2, BigDecimal.ROUND_HALF_UP);
            PriceResult priceResult = priceUtil.eur2Rmb(price);
            price = priceResult.getPrice();
            
            
            // 品牌对应
            StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand :: getEnName, product.getBrand())
                    .eq(StoreBrand :: getType, ProductTypeEnum.COLTORTI)
                    .last("LIMIT 1")
                    );
            storeBrandService.unMatchBrand(buyerStoreBrand,null,product.getBrand(),ProductTypeEnum.COLTORTI);
            StoreBrand storeBrand = null;
            if(null != buyerStoreBrand) {
                if(null != buyerStoreBrand.getSuperId()) {
                    storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
                } else {
                    storeBrand = storeBrandService.getById(5429);
                }
            } else {
                storeBrand = storeBrandService.getById(5429);
            }
            
            /***** 处理对象构建 *******/
            String barCode = BarCodeEnum.COLTORTI.getCode() + product.getSkuStyleisnow();
            List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();
            // 规格
            StoreProductAttr storeProductAttr = new StoreProductAttr();
            storeProductAttr.setAttrName("尺寸");
            storeProductAttr.setType(0);
            storeProductAttr.setBarCode(barCode);
            // 颜色
            StoreProductAttr storeProductAttrColor = new StoreProductAttr();
            storeProductAttrColor.setAttrName("颜色");
            storeProductAttrColor.setType(0);
            storeProductAttrColor.setBarCode(barCode);
            // 合并成suk
            String[] sizes = product.getSize().split(",");
            String[] qtys = product.getQtyDetail().split(",");
            
            List<String> colorValueList = new ArrayList<String>();
            List<String> valueList = new ArrayList<String>();
            for(int i=0; i<sizes.length; i++) {
                int qty = Integer.parseInt(qtys[i]);
                if(0 >= qty) {
                    continue;
                }
                // value对象
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setSourceSkuId(product.getSkuStyleisnow() + "-" + sizes[i]);
                
                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                List<String> suk = new ArrayList<String>();
                linkedMap.put("颜色", product.getColorSupplier());
                if (!colorValueList.contains(product.getColorSupplier())) {
                    colorValueList.add(product.getColorSupplier());
                }
                suk.add(product.getColorSupplier());
                linkedMap.put("尺寸", sizes[i]);
                if (!valueList.contains(sizes[i])) {
                    valueList.add(sizes[i]);
                }
                suk.add(sizes[i]);
                storeProductAttrValue.setSuk(String.join(",", suk));
                storeProductAttrValue.setAttrValue(linkedMap);
                storeProductAttrValue.setStock(qty);
                storeProductAttrValue.setPrice(price);
                storeProductAttrValue.setImage(mainImage);
                storeProductAttrValue.setCost(price);
                storeProductAttrValue.setSourceCost(price);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(otPrice);
                storeProductAttrValue.setTempId(StockAreaTempEnum.EUR.getTempId());
                attrValueList.add(storeProductAttrValue);
            }
            // attr对象
            if (CollectionUtils.isNotEmpty(colorValueList)) {
                storeProductAttrColor.setAttrValues(String.join(",", colorValueList));
                attrList.add(storeProductAttrColor);
            }
            if (CollectionUtils.isNotEmpty(valueList)) {
                storeProductAttr.setAttrValues(String.join(",", valueList));
                attrList.add(storeProductAttr);
            }
            
//            productRequest = new StoreProductCrmebRequest();
            productRequest.setExchangeRate(priceResult.getExchangeRate());
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.COLTORTI.getMerchantId());
            productRequest.setKeyword(keyword);
            productRequest.setStoreInfo(product.getDescription());
            productRequest.setContent(product.getDescription());
            productRequest.setStoreName(product.getName());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(price);
            productRequest.setOtPrice(otPrice);
            productRequest.setCost(price);
            productRequest.setSourceCost(price);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(StockAreaTempEnum.EUR.getTempId());
            
//            // 供应商
//            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
//                    .eq(Supplier :: getSuppliersName, CrmebMerchantEnums.COLTORTI.getMerchantName())
//                    .last("LIMIT 1")
//                    );
//            if(null != supplier) {
//                productRequest.setSuppliersId(supplier.getId().toString());
//                productRequest.setSuppliersName(supplier.getSuppliersName());
//            }
            productRequest.setBarCode(barCode);
            // 分类
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch :: getType, CategoryTypeEnum.COLTORTI)
                    .eq(CategoryMatch :: getOthCategoryName, product.getCategories())
                    .last("LIMIT 1")
                    );
            categoryMatchService.unMatchCategory(categoryMatch,null,product.getCategories(),null,CategoryTypeEnum.COLTORTI);
            // 复制重量
            if(null != categoryMatch) {
            	CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
            	categoryMatch.setWeight(Optional.ofNullable(supCategoryMatch).orElse(new CategoryMatch()).getWeight());
            }
            Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 1859;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Arrays.asList(categoryId));
            productRequest.setWeight(null != categoryMatch ? categoryMatch.getWeight() : BigDecimal.ONE);
            productRequest.setImage(mainImage);
            if(gallery.size() > 0) {
                productRequest.setSliderImage(JSON.toJSONString(gallery));
            }
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.COLTORTI.getCode());
            productRequest.setUnitName("件");
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
            productRequest.setColorCode(product.getColorSupplier());
            productRequest.setSeasonCode(product.getYear() + product.getSeason());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return productRequest;
    }

}
